package com.czp.infosharingplatformapp.service.impl;

import com.czp.infosharingplatformapp.dto.CategoryResponse;
import com.czp.infosharingplatformapp.model.*;
import com.czp.infosharingplatformapp.repository.*;
import com.czp.infosharingplatformapp.dto.PostResponse;
import com.czp.infosharingplatformapp.service.CategoryService;
import com.czp.infosharingplatformapp.service.CommentService;
import com.czp.infosharingplatformapp.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private ResourceRepository resourceRepository;

    @Autowired
    private CategoryService categoryService;

    @Override
    public Post createPost(String title, String content, Long userId, Long categoryId, Long resourceId, List<PostTag> tags) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        Category category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new RuntimeException("分类不存在"));

        Resource resource = null;
        if (resourceId != null) {
            resource = resourceRepository.findById(resourceId)
                    .orElseThrow(() -> new RuntimeException("资源不存在"));
        }

        Post post = new Post();
        post.setTitle(title);
        post.setContent(content);
        post.setUser(user);
        post.setCategory(category);
        post.setResource(resource);
        post.setTags(tags);
        for (PostTag tag : tags) {
            tag.setPost(post); // 每个标签关联当前帖子
        }
        return postRepository.save(post);
    }

    @Override
    public List<Post> getAllPosts() {
        return postRepository.findAll();
    }

    @Override
    public void deletePost(Long postId) {
        if (!postRepository.existsById(postId)) {
            throw new RuntimeException("帖子不存在");
        }
        postRepository.deleteById(postId); // 删除帖子
    }

    @Override
    public List<Post> searchPosts(String keyword) {
        return postRepository.findAll().stream()
                .filter(post -> post.getTitle().contains(keyword)
                        || post.getContent().contains(keyword)
                        || (post.getCategory() != null && post.getCategory().getName().contains(keyword))
                        || (post.getResource() != null && post.getResource().getFileName().contains(keyword))
                        || (post.getResource() != null && post.getResource().getDescription().contains(keyword))
                        || post.getTags().stream().anyMatch(tag -> tag.getTag().contains(keyword)))
                .collect(Collectors.toList());
    }

    @Override
    public List<Post> filterPostsByCategory(Long categoryId) {
        return postRepository.findAll().stream()
                .filter(post -> post.getCategory() != null && post.getCategory().getId().equals(categoryId))
                .collect(Collectors.toList());
    }

    @Override
    public Post getPostById(Long id) {
        Optional<Post> postOptional = postRepository.findById(id);
        if (postOptional.isPresent()) {
            return postOptional.get();
        } else {
            throw new RuntimeException("Post not found");
        }
    }

    @Override
    public PostResponse convertToPostResponse(Post post) {
        PostResponse response = new PostResponse();
        response.setId(post.getId());
        response.setTitle(post.getTitle());
        response.setContent(post.getContent());

        User author = post.getUser();
        if (author != null) {
            response.setAuthorId(author.getId());
            response.setAuthorUsername(author.getUsername());
        }

        Resource resource = post.getResource();
        if (resource != null) {
            response.setResourceId(resource.getId());
            response.setResourceFileName(resource.getFileName());
            response.setResourceDescription(resource.getDescription());
        }

        response.setCreatedAt(post.getCreatedAt());
        response.setTags(post.getTags().stream().map(PostTag::getTag).collect(Collectors.toList()));

        Category category = post.getCategory();
        if (category != null) {
            CategoryResponse categoryResponse = categoryService.convertToCategoryResponse(category);
            response.setCategory(categoryResponse);
        }

        return response;
    }
}